package com.company.cloud.web.render;

import java.io.IOException;
import java.io.PrintWriter;

public class TextRender extends Render{

    // 与 encoding 与 contentType 在 render() 方法中分开设置，效果相同
//    protected static final String DEFAULT_CONTENT_TYPE = "text/plain";


    protected String text;

    protected String contentType;

    public TextRender(String text){
        this.text=text;
        this.contentType=ContentType.TEXT.value();
    }

    public TextRender(String text,String contentType){
        this.text=text;
        ContentType ct = ContentType.parse(contentType);
        this.contentType = (ct != null ? ct.value() : contentType);
    }

    public TextRender(String text,ContentType contentType){
        this.text=text;
        this.contentType = contentType.value();
    }

    @Override
    public void render() {
        PrintWriter writer=null;
        try {
            String ct=getContentType();
            response.setContentType(ct);
            if(ct.indexOf("charset")==-1){
                response.setCharacterEncoding(getEncoding());
            }
            writer=response.getWriter();
            writer.write(text);
            writer.flush();;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getText() {
        return text;
    }

    public String getContentType() {
        return contentType;
    }

}
